import { useEffect, useRef } from 'react';
import { Webview, getCurrentWebview } from "@tauri-apps/api/webview";
import { LogicalSize } from '@tauri-apps/api/window';

function WebView(props: { url: string, className?: string,id:string,visible?:boolean }) {
  const { url,visible=true ,id} = props
  const key = useRef(props.id||(Math.random()*1000).toFixed(0))
  const webviewContainerRef = useRef<HTMLDivElement>(null);
  const webviewRef = useRef<Webview>();

  const handleResize = () => {
    const rect = webviewContainerRef.current?.getBoundingClientRect?.();

    if (!rect) return

    if (webviewRef.current) {
      console.log("%c Line:18 🍻", "color:#3f7cff",id, '重设窗口大小');
      webviewRef.current.setSize(new LogicalSize(rect.width, rect.height))
    } else {
      console.log("%c Line:18 🍻", "color:#3f7cff", id,'创建窗口');
      const appWindow = getCurrentWebview().window;
      webviewRef.current = new Webview(appWindow, key.current, {
        width: rect.width,
        height: rect.height,
        x: rect.left,
        y: rect.top,
        url: url,
      });

      if(!visible){
        webviewRef.current.hide()
      }
      
      webviewRef.current.once("tauri://created",  function() {
        console.log("%c Line:30 🍻 tauri://created", "color:#ffdd4d",id,'创建成功' );
        if(!visible){
          webviewRef.current?.hide?.()
        }
      });
      webviewRef.current.once("tauri://error", function (e) {
        console.error("%c Line:34 🍻 error", "color:#7f2b82",id,  e);
        // an error happened creating the webview
      });
      console.log("%c Line:35 🍻 new Webview", "color:#ed9ec7", webviewRef.current, {
        width: rect.width,
        height: rect.height,
        x: rect.left,
        y: rect.top,
        url: url,
      });
    }
  }


  useEffect(() => {
    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        if (entry.target === webviewContainerRef.current) {
          handleResize()
        }
      }

    })

    if (webviewContainerRef.current) {
      resizeObserver.observe(webviewContainerRef.current)
    }

    return () => {
      if (webviewContainerRef.current) {
        resizeObserver.unobserve(webviewContainerRef.current)
      }

      if(webviewRef.current){
        webviewRef.current?.close?.()
      }
    }
  }, [])

  useEffect(()=>{
    console.log("%c Line:81 🍆 visible", "color:#4fff4B",id, visible);
    if(visible){
      webviewRef.current?.show()
    }else{
      webviewRef.current?.hide()
    }
  },[visible])

  return (
    <div className={props.className} ref={webviewContainerRef} >
      {/* The actual webview will be rendered by Tauri */}
    </div>
  );
}

export default WebView;